// 文件上传相关
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('script_file');
const fileList = document.getElementById('fileList');
const fileCount = document.getElementById('fileCount');
const uploadForm = document.getElementById('uploadForm');

// 处理拖放
dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
});

dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    const items = e.dataTransfer.items;
    if (items) {
        fileInput.files = e.dataTransfer.files;
        updateFileList();
    }
});

// 点击上传区域触发文件选择
dropZone.addEventListener('click', () => {
    fileInput.click();
});

fileInput.addEventListener('change', updateFileList);

function updateFileList() {
    const files = fileInput.files;
    fileList.innerHTML = '';
    
    if (files.length > 0) {
        const pythonFiles = Array.from(files).filter(file => file.name.toLowerCase().endsWith('.py'));
        
        // 显示文件列表
        Array.from(files).slice(0, 5).forEach(file => {
            const item = document.createElement('div');
            item.className = 'file-list-item';
            item.textContent = file.name;
            fileList.appendChild(item);
        });

        if (files.length > 5) {
            const item = document.createElement('div');
            item.className = 'file-list-item';
            item.textContent = `... 还有 ${files.length - 5} 个文件`;
            fileList.appendChild(item);
        }

        fileCount.textContent = `共 ${files.length} 个文件，其中 ${pythonFiles.length} 个Python文件`;
        
        // 如果没有Python文件，显示警告
        if (pythonFiles.length === 0) {
            fileCount.innerHTML += '<br><span style="color: red;">警告：未发现Python文件！</span>';
        }
    } else {
        fileCount.textContent = '';
    }
}

// 脚本运行相关
function runScript(name) {
    const outputDiv = document.getElementById(`output-${name}`);
    outputDiv.style.display = 'block';
    outputDiv.textContent = '运行中...';
    
    fetch(`/run_script/${name}`)
        .then(response => response.json())
        .then(data => {
            let output = '';
            if (data.error) {
                output = `错误: ${data.error}`;
            } else {
                output = `退出码: ${data.returncode}\n\n`;
                if (data.stdout) output += `输出:\n${data.stdout}\n`;
                if (data.stderr) output += `错误:\n${data.stderr}`;
            }
            outputDiv.textContent = output;
        })
        .catch(error => {
            outputDiv.textContent = `运行出错: ${error}`;
        });
} 